//
//  CollectionHandle.m
//  DailyNews
//
//  Created by 于跃隆 on 2018/12/21.
//  Copyright © 2018年 于跃隆. All rights reserved.
//

#import "CollectionHandle.h"

static CollectionHandle *_dataBase = nil;

@interface CollectionHandle ()<NSCopying>{
    FMDatabase *_dbManager;
}

@end

@implementation CollectionHandle
//GCD 单例
//这个方法服务于alloc 无论外界调用多少次alloc 返回的都是一个内存空间
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dataBase = [super allocWithZone:zone];
    });
    return _dataBase;
}
//共享方法，便于外界调用
//但是避免不了外界init多次，所以要带入init，这里的alloc会调用上面的方法
+(instancetype)sharedDBManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dataBase = [[CollectionHandle alloc]init];
    });
    return _dataBase;
}
//这个方法避免外界实现copy方法（这里要遵循NSCopying协议）
-(id)copyWithZone:(NSZone *)zone{
    return _dataBase;
}
-(id)init{
    if (self = [super init]) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        //数据库路径
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"http.db"];
        NSLog(@"地址：%@",filePath);
        //创建数据库
        _dbManager = [[FMDatabase alloc]initWithPath:filePath];
        
        if ([_dbManager open]) {
            NSLog(@"数据库打开成功！");
            //创建数据表格
            [self createDataTable];
        }else{
            NSLog(@"数据库打开失败%@",_dbManager.lastErrorMessage);
        }
        [_dbManager close];
        
    }
    return self;
}
-(void)createDataTable{
    NSString *sql = @"create table if not exists httpInfo(category text,author_name text,date text,title text,thumbnail_pic_s text,url text)";
    BOOL isSuccess = [_dbManager executeUpdate:sql];
    if (!isSuccess) {
        NSLog(@"创建表失败：%@",_dbManager.lastErrorMessage);
    }
}
//增添数据
-(void)insertModel:(id)httpModel{
    [_dbManager open];
    HttpHandle *http = (HttpHandle *)httpModel;
    NSString *sql = @"insert into httpInfo(category,author_name,date,title,thumbnail_pic_s,url)values(?,?,?,?,?,?)";
    BOOL isSuccess = [_dbManager executeUpdate:sql,http.category,http.author_name,http.date,http.title,http.thumbnail_pic_s,http.url];
    if (!isSuccess) {
        NSLog(@"增加数据失败:%@",_dbManager.lastErrorMessage);
    }
    [_dbManager close];
}
//删除数据
-(void)deleteModelByName:(NSString *)name{
    [_dbManager open];
    NSString *sql = @"delete from httpInfo where author_name = ?";
    BOOL isSuccess = [_dbManager executeUpdate:sql,name];
    if (!isSuccess) {
        NSLog(@"删除数据失败:%@",_dbManager.lastErrorMessage);
    }
    [_dbManager close];
}
-(void)updateModel:(HttpHandle *)httpModel{
    [_dbManager open];
    //category,author_name,date,title,thumbnail_pic_s,url
    NSString *sql = @"update httpInfo set category = ?,date = ?,title = ?,thumbnail_pic_s = ?,url = ? where author_name = ?";
    BOOL isSuccess = [_dbManager executeUpdate:sql,httpModel.category,httpModel.date,httpModel.title,httpModel.thumbnail_pic_s,httpModel.url,httpModel.author_name];
    if (!isSuccess) {
        NSLog(@"更新数据失败%@",_dbManager.lastErrorMessage);
    }
    [_dbManager close];
}
-(NSMutableArray *)fetchAll{
    [_dbManager open];
    NSMutableArray *arr = [NSMutableArray array];
    NSString *sql = @"select * from httpInfo";
    FMResultSet *rest = [_dbManager executeQuery:sql];
    while ([rest next]) {
        HttpHandle *http = [[HttpHandle alloc]init];
        //category,author_name,date,title,thumbnail_pic_s,url
        http.category = [rest stringForColumn:@"category"];
        http.author_name = [rest stringForColumn:@"author_name"];
        http.date = [rest stringForColumn:@"date"];
        http.title = [rest stringForColumn:@"title"];
        http.thumbnail_pic_s = [rest stringForColumn:@"thumbnail_pic_s"];
        http.url = [rest stringForColumn:@"url"];
        
        [arr addObject:http];
    }
    [_dbManager close];
    return arr;
}

@end
